package com.jsite.modules.sys.security;

import com.jsite.common.utils.SpringContextHolder;
import com.jsite.modules.sys.entity.Principal;
import com.jsite.modules.sys.utils.UserUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


public class SystemLogoutFilter extends LogoutFilter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private SystemAuthorizingRealm systemAuthorizingRealm;

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        logger.debug("SystemLogoutFilter------------>>>>>>>>>>>>>>>>>");
        UserUtils.clearCache();
        //登出操作 清除缓存  subject.logout() 可以自动清理缓存信息, 这些代码是可以省略的  这里只是做个笔记 表示这种方式也可以清除
        Subject subject = getSubject(request,response);
        Principal principal = (Principal)subject.getPrincipal();
        //登出
        subject.logout();

        //用户修改密码之后，shiro中还有缓存，清除掉之后才能用新密码登录
        Cache<Object, AuthenticationInfo> cache= getSystemAuthorizingRealm().getAuthenticationCache();
        if (cache!=null && principal != null){
            cache.remove(principal.getLoginName());
        }

        //获取登出后重定向到的地址
        String redirectUrl = getRedirectUrl(request,response,subject);
        //重定向
        issueRedirect(request,response,redirectUrl);
        return false;
    }

    private SystemAuthorizingRealm getSystemAuthorizingRealm() {
        if (systemAuthorizingRealm == null){
            systemAuthorizingRealm = SpringContextHolder.getBean(SystemAuthorizingRealm.class);
        }
        return systemAuthorizingRealm;
    }
}
